<template>
  <div class="branch-meeting-container">
    <div class="page-header">
      <h2>支部大会信息管理</h2>
      <p>管理党支部大会、组织生活会等会议信息</p>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-blue">
              <el-icon>
                <Connection />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalCount }}</div>
              <div class="stat-label">会议总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-green">
              <el-icon>
                <Calendar />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.thisMonthCount }}</div>
              <div class="stat-label">本月会议数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-orange">
              <el-icon>
                <User />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.avgAttendance }}</div>
              <div class="stat-label">平均参会率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-purple">
              <el-icon>
                <Document />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.pendingCount }}</div>
              <div class="stat-label">待召开会议</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="会议主题">
            <el-input v-model="searchForm.meetingTheme" placeholder="请输入会议主题" clearable
              @clear="handleInputClear('meetingTheme')" @input="debounceSearch" />
          </el-form-item>
          <el-form-item label="会议类型">
            <el-select v-model="searchForm.meetingType" placeholder="请选择会议类型" clearable style="width: 100%"
              @change="handleTypeChange">
              <el-option label="支部党员大会" :value="1" />
              <el-option label="支部委员会" :value="2" />
              <el-option label="党小组会" :value="3" />
              <el-option label="党课" :value="4" />
              <el-option label="组织生活会" :value="5" />
              <el-option label="民主评议会" :value="6" />
            </el-select>
          </el-form-item>
          <el-form-item label="会议状态">
            <el-select v-model="searchForm.meetingStatus" placeholder="请选择状态" clearable style="width: 100%"
              @change="handleStatusChange">
              <el-option label="筹备中" :value="0" />
              <el-option label="待召开" :value="1" />
              <el-option label="已召开" :value="2" />
              <el-option label="已取消" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchMeetings">
              <el-icon>
                <Search />
              </el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon>
                <Refresh />
              </el-icon> 重置
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon>
                <Plus />
              </el-icon> 新增会议
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 会议列表表格 -->
    <el-card class="table-card" shadow="hover" v-loading="loading">
      <el-table :data="meetingList" border style="width: 100%" row-key="id">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="meetingTheme" label="会议主题" min-width="180" />
        <el-table-column prop="meetingType" label="会议类型" min-width="120">
          <template #default="scope">
            {{ getTypeText(scope.row.meetingType) }}
          </template>
        </el-table-column>
        <el-table-column prop="meetingDate" label="召开日期" min-width="100" />
        <el-table-column prop="meetingPlace" label="会议地点" min-width="120" />
        <el-table-column prop="meetingStatus" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.meetingStatus)">{{ getStatusText(scope.row.meetingStatus)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" plain @click="handleView(scope.row)">
                <el-icon>
                  <View />
                </el-icon> 查看
              </el-button>
              <el-button size="small" type="warning" plain @click="handleEdit(scope.row)"
                v-if="scope.row.meetingStatus !== 20">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <el-button size="small" type="info" plain @click="handleMinutes(scope.row)"
                v-if="scope.row.meetingStatus === 20">
                <el-icon>
                  <Document />
                </el-icon> 会议纪要
              </el-button>
              <el-button size="small" type="danger" plain @click="handleDelete(scope.row)"
                v-if="scope.row.meetingStatus !== 20">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看会议详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="会议详情" width="800px" :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="会议主题">{{ currentMeeting.meetingTheme }}</el-descriptions-item>
        <el-descriptions-item label="会议类型">{{ getTypeText(currentMeeting.meetingType) }}</el-descriptions-item>
        <el-descriptions-item label="召开日期">{{ currentMeeting.meetingDate }}</el-descriptions-item>
        <el-descriptions-item label="会议地点">{{ currentMeeting.meetingPlace }}</el-descriptions-item>
        <el-descriptions-item label="会议状态">
          <el-tag :type="getStatusTagType(currentMeeting.meetingStatus)">{{ getStatusText(currentMeeting.meetingStatus)
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="参会人数" v-if="currentMeeting.meetingPeople">
          {{ currentMeeting.meetingPeople.length }} 人
        </el-descriptions-item>
        <el-descriptions-item label="参会人员" :span="2"
          v-if="currentMeeting.meetingPeople && currentMeeting.meetingPeople.length > 0">
          <div class="meeting-people">
            {{ getUserNamesById(currentMeeting.meetingPeople) }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="会议纪要" :span="2" v-if="currentMeeting.filePath">
          <div class="file-preview">
            <div v-if="isImageFile(currentMeeting.filePath)">
              <el-image :src="currentMeeting.filePath" fit="contain"
                :preview-src-list="[currentMeeting.filePath]"></el-image>
            </div>
            <div v-else>
              <el-button type="primary" @click="downloadFile(currentMeeting.filePath)">
                <el-icon>
                  <Download />
                </el-icon> 下载会议纪要
              </el-button>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" v-if="currentMeeting.createTime">
          {{ formatDateTime(currentMeeting.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" v-if="currentMeeting.updateTime">
          {{ formatDateTime(currentMeeting.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑会议对话框 -->
    <el-dialog v-model="editDialogVisible" :title="isEdit ? '编辑会议' : '新增会议'" width="800px"
      :close-on-click-modal="false">
      <el-form :model="meetingForm" :rules="meetingFormRules" ref="meetingFormRef" label-width="100px">
        <el-form-item label="会议主题" prop="meetingTheme">
          <el-input v-model="meetingForm.meetingTheme" placeholder="请输入会议主题" />
        </el-form-item>
        <el-form-item label="会议类型" prop="meetingType">
          <el-select v-model="meetingForm.meetingType" placeholder="请选择会议类型" style="width: 100%">
            <el-option label="支部党员大会" :value="1" />
            <el-option label="支部委员会" :value="2" />
            <el-option label="党小组会" :value="3" />
            <el-option label="党课" :value="4" />
            <el-option label="组织生活会" :value="5" />
            <el-option label="民主评议会" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item label="召开日期" prop="meetingDate">
          <el-date-picker v-model="meetingForm.meetingDate" type="date" placeholder="请选择召开日期" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="会议地点" prop="meetingPlace">
          <el-input v-model="meetingForm.meetingPlace" placeholder="请输入会议地点" />
        </el-form-item>
        <el-form-item label="会议状态" prop="meetingStatus">
          <el-select v-model="meetingForm.meetingStatus" placeholder="请选择会议状态" style="width: 100%">
            <el-option label="筹备中" :value="0" />
            <el-option label="待召开" :value="1" />
            <el-option label="已召开" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="参会人员" prop="meetingPeople">
          <el-select v-model="meetingForm.meetingPeople" multiple filterable placeholder="请选择参会人员"
            :loading="userLoading" style="width: 100%">
            <el-option v-for="user in userList" :key="user.id"
              :label="user.name || user.username || user.nickname || '用户' + user.id" :value="user.id" />
          </el-select>
          <div v-if="meetingForm.meetingPeople && meetingForm.meetingPeople.length > 0" class="selected-users-info">
            已选择 {{ meetingForm.meetingPeople.length }} 人参会
          </div>
        </el-form-item>
        <el-form-item label="会议纪要" prop="filePath" v-if="meetingForm.meetingStatus === 2">
          <el-upload class="upload-demo" action="/api/user/uploadImage" :on-success="handleUploadSuccess"
            :on-error="handleUploadError" :before-upload="beforeUpload">
            <el-button type="primary">上传会议纪要</el-button>
            <template #tip>
              <div class="el-upload__tip">支持jpg、png、pdf、doc、docx等格式文件</div>
            </template>
          </el-upload>
          <div v-if="meetingForm.filePath" class="file-preview">
            <div class="file-info">
              已上传: {{ getFileName(meetingForm.filePath) }}
              <el-button type="danger" link @click="meetingForm.filePath = ''">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMeeting" :loading="submitting">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 签到管理对话框 -->
    <el-dialog v-model="attendanceDialogVisible" title="签到管理" width="900px" :close-on-click-modal="false">
      <div class="attendance-management">
        <div class="attendance-search">
          <el-input v-model="attendanceSearchKeyword" placeholder="搜索党员姓名" clearable :prefix-icon="Search"
            @input="searchAttendees" />
          <el-button type="primary" @click="handleAddAttendees">
            <el-icon>
              <Plus />
            </el-icon> 添加党员
          </el-button>
        </div>

        <el-table :data="attendeeList" border style="width: 100%" v-loading="attendeesLoading">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="department" label="所属部门" min-width="120" />
          <el-table-column prop="position" label="职务" min-width="100" />
          <el-table-column prop="attendance_status" label="签到状态" min-width="120">
            <template #default="scope">
              <el-select v-model="scope.row.attendance_status" @change="handleAttendanceStatusChange(scope.row)">
                <el-option label="已签到" value="present" />
                <el-option label="请假" value="leave" />
                <el-option label="缺席" value="absent" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="leave_reason" label="请假原因" min-width="150">
            <template #default="scope">
              <el-input v-model="scope.row.leave_reason" :disabled="scope.row.attendance_status !== 'leave'"
                placeholder="请输入请假原因" @change="handleLeaveReasonChange(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="sign_time" label="签到时间" min-width="120" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" plain @click="handleRemoveAttendee(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon> 移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="attendanceDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="saveAttendance">保存签到</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加党员对话框 -->
    <el-dialog v-model="addAttendeesDialogVisible" title="添加党员" width="800px" append-to-body
      :close-on-click-modal="false">
      <div class="add-attendees">
        <el-input v-model="addAttendeeKeyword" placeholder="搜索党员姓名或部门" clearable :prefix-icon="Search"
          style="margin-bottom: 15px" />

        <el-table :data="availableAttendees" border style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="department" label="所属部门" min-width="120" />
          <el-table-column prop="position" label="职务" min-width="100" />
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addAttendeesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddAttendees">确认添加</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 会议纪要对话框 -->
    <el-dialog v-model="minutesDialogVisible" title="会议纪要" width="800px" :close-on-click-modal="false">
      <el-form :model="minutesForm" :rules="minutesFormRules" ref="minutesFormRef" label-width="100px">
        <el-form-item label="会议主题">
          <el-input v-model="currentMeeting.meetingTheme" disabled />
        </el-form-item>
        <el-form-item label="召开日期">
          <el-input v-model="currentMeeting.meetingDate" disabled />
        </el-form-item>
        <el-form-item label="实际参会" prop="actual_count">
          <el-input-number v-model="minutesForm.actual_count" :min="0" :max="currentMeeting.expected_count" />
          /{{ currentMeeting.expected_count }}
        </el-form-item>
        <el-form-item label="主要议题" prop="topics">
          <el-input v-model="minutesForm.topics" type="textarea" :rows="3" placeholder="请输入主要议题" />
        </el-form-item>
        <el-form-item label="讨论情况" prop="discussion">
          <el-input v-model="minutesForm.discussion" type="textarea" :rows="5" placeholder="请输入讨论情况" />
        </el-form-item>
        <el-form-item label="会议决议" prop="resolution">
          <el-input v-model="minutesForm.resolution" type="textarea" :rows="5" placeholder="请输入会议决议" />
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload action="#" list-type="text" :auto-upload="false" :file-list="minutesForm.files"
            :on-change="handleFileChange" :on-remove="handleFileRemove">
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">可上传会议照片、签到表等文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="minutesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMinutes" :loading="submitting">保存纪要</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search, Refresh, View, Edit, Delete, Plus, Connection,
  User, UserFilled, Calendar, Document, Setting, Download
} from '@element-plus/icons-vue';
import {
  getMeetingLogList,
  getMeetingLogById,
  addMeetingLog,
  updateMeetingLog,
  deleteMeetingLog
} from '@/api/meetingLog';
import { getUserList } from '@/api/user';

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const meetingList = ref([]);

// 统计数据
const statsData = reactive({
  totalCount: 0,
  thisMonthCount: 0,
  avgAttendance: 0,
  pendingCount: 0
});

// 搜索表单
const searchForm = reactive({
  meetingTheme: '',
  meetingType: '',
  meetingStatus: ''
});

// 详情对话框
const viewDialogVisible = ref(false);
const currentMeeting = ref({});

// 编辑对话框
const editDialogVisible = ref(false);
const isEdit = ref(false);
const meetingFormRef = ref(null);
const submitting = ref(false);
const meetingForm = reactive({
  id: '',
  meetingTheme: '',
  meetingType: '',
  meetingDate: '',
  meetingTime: '',
  meetingPlace: '',
  meetingStatus: 0,
  expected_count: 0,
  attendance_count: 0,
  agenda: '',
  content: '',
  resolution: '',
  filePath: '',
  meetingPeople: [],
  createTime: '',
  updateTime: ''
});

// 表单校验规则
const meetingFormRules = {
  meetingTheme: [{ required: true, message: '请输入会议主题', trigger: 'blur' }],
  meetingType: [{ required: true, message: '请选择会议类型', trigger: 'change' }],
  meetingDate: [{ required: true, message: '请选择召开日期', trigger: 'change' }],
  meetingPlace: [{ required: true, message: '请输入会议地点', trigger: 'blur' }],
  meetingStatus: [{ required: true, message: '请选择会议状态', trigger: 'change' }],
  meetingPeople: [{ required: true, message: '请选择参会人员', trigger: 'change' }]
};

// 签到管理相关
const attendanceDialogVisible = ref(false);
const attendanceSearchKeyword = ref('');
const attendeesLoading = ref(false);
const attendeeList = ref([]);
const addAttendeesDialogVisible = ref(false);
const addAttendeeKeyword = ref('');
const selectedAttendees = ref([]);
const availableAttendees = ref([]);

// 会议纪要相关
const minutesDialogVisible = ref(false);
const minutesFormRef = ref(null);
const minutesForm = reactive({
  id: '',
  actual_count: 0,
  topics: '',
  discussion: '',
  resolution: '',
  files: []
});

// 会议纪要表单校验规则
const minutesFormRules = {
  actual_count: [{ required: true, message: '请输入实际参会人数', trigger: 'blur' }],
  topics: [{ required: true, message: '请输入主要议题', trigger: 'blur' }],
  discussion: [{ required: true, message: '请输入讨论情况', trigger: 'blur' }],
  resolution: [{ required: true, message: '请输入会议决议', trigger: 'blur' }]
};

const formatDate = (dateTimeStr, includeTime = false) => {
  if (!dateTimeStr) return '-';
  // 后端返回的是 LocalDateTime 字符串，通常是 "YYYY-MM-DDTHH:mm:ss" 或 "YYYY-MM-DD HH:mm:ss"
  if (includeTime) {
    return dateTimeStr.replace('T', ' ').substring(0, 19); // YYYY-MM-DD HH:mm:ss
  }
  return dateTimeStr.substring(0, 10); // YYYY-MM-DD
};

// 用户数据相关
const userList = ref([]);
const userLoading = ref(false);

// 初始化加载数据
onMounted(() => {
  fetchMeetings();
  fetchAllUsers(); // 加载用户数据
});

// 获取会议列表
const fetchMeetings = async () => {
  loading.value = true;
  try {
    // 构建查询条件
    const queryData = {
      meetingTheme: searchForm.meetingTheme,
      meetingType: searchForm.meetingType,
      meetingStatus: searchForm.meetingStatus
    };

    // 调用API获取数据
    const response = await getMeetingLogList(queryData, currentPage.value, pageSize.value);

    if (response.data.code === 200) {
      const data = response.data.data || {};
      meetingList.value = data.page?.records || [];
      for (var i = 0; i < meetingList.value.length; ++i) {
        meetingList.value[i].meetingDate = formatDate(meetingList.value[i].meetingDate, false);
      }
      total.value = data.total || 0;

      // 更新统计数据
      updateStatsData();
    } else {
      ElMessage.error(response.data.msg || '获取会议列表失败');
      meetingList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取会议列表失败:', error);
    ElMessage.error('获取会议列表失败，请稍后重试');
    meetingList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 更新统计数据
const updateStatsData = () => {
  // 计算总数
  statsData.totalCount = meetingList.value.length;

  // 计算本月会议数
  const currentMonth = new Date().getMonth() + 1;
  const currentYear = new Date().getFullYear();
  statsData.thisMonthCount = meetingList.value.filter(item => {
    const meetingDate = new Date(item.meetingDate);
    return meetingDate.getMonth() + 1 === currentMonth &&
      meetingDate.getFullYear() === currentYear;
  }).length;

  // 计算平均参会率 (移除此统计或更改统计方式)
  statsData.avgAttendance = 0;

  // 计算待召开会议数量
  statsData.pendingCount = meetingList.value.filter(item =>
    item.meetingStatus === 1 || item.meetingStatus === 0
  ).length;
};

// 搜索会议
const searchMeetings = () => {
  currentPage.value = 1;
  fetchMeetings();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
  fetchMeetings();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchMeetings();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchMeetings();
};

// 处理输入框清除
const handleInputClear = (key) => {
  searchForm[key] = '';
  fetchMeetings();
};

// 处理类型变化
const handleTypeChange = () => {
  fetchMeetings();
};

// 处理状态变化
const handleStatusChange = () => {
  fetchMeetings();
};

// 获取会议类型文本
const getTypeText = (type) => {
  const types = {
    1: '支部党员大会',
    2: '支部委员会',
    3: '党小组会',
    4: '党课',
    5: '组织生活会',
    6: '民主评议会'
  };
  return types[type] || type;
};

// 获取状态文本
const getStatusText = (status) => {
  const statuses = {
    0: '筹备中',
    1: '待召开',
    2: '已召开',
    3: '已取消'
  };
  return statuses[status] || status;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  };
  return types[status] || '';
};

// 获取参会率颜色
const getAttendanceColor = (rate) => {
  if (rate >= 90) return '#67C23A';
  if (rate >= 75) return '#E6A23C';
  return '#F56C6C';
};

// 查看会议详情
const handleView = async (row) => {
  try {
    loading.value = true;
    // 调用API获取详细数据
    const response = await getMeetingLogById(row.id);

    if (response.data.code === 200) {
      currentMeeting.value = response.data.data || {};
      currentMeeting.value.meetingDate = formatDate(currentMeeting.value.meetingDate, false);
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || '获取会议详情失败');
    }
  } catch (error) {
    console.error('获取会议详情失败:', error);
    ElMessage.error('获取会议详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 获取所有用户
const fetchAllUsers = async () => {
  userLoading.value = true;
  try {
    const response = await getUserList({}, 1, 100);
    if (response.data.code === 200) {
      userList.value = response.data.data.users || [];
    } else {
      ElMessage.error(response.data.msg || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    userLoading.value = false;
  }
};

// 获取用户姓名
const getUserNameById = (userId) => {
  const user = userList.value.find(u => u.id === userId);
  return user ? (user.name || user.username || user.nickname || `用户${userId}`) : `用户${userId}`;
};

// 获取用户姓名（多个用户）
const getUserNamesById = (userIds) => {
  if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
    return '无';
  }

  return userIds.map(id => getUserNameById(id)).join(', ');
};

// 新增会议
const handleAdd = () => {
  isEdit.value = false;
  Object.keys(meetingForm).forEach(key => {
    if (key === 'meetingStatus') {
      meetingForm[key] = 0;
    } else if (key === 'meetingPeople') {
      meetingForm[key] = [];
    } else if (key === 'filePath') {
      meetingForm[key] = '';
    } else {
      meetingForm[key] = '';
    }
  });
  editDialogVisible.value = true;

  // 确保用户列表已加载
  if (userList.value.length === 0) {
    fetchAllUsers();
  }
};

// 编辑会议
const handleEdit = async (row) => {
  try {
    loading.value = true;
    // 调用API获取详细数据
    const response = await getMeetingLogById(row.id);

    if (response.data.code === 200) {
      const meetingData = response.data.data || {};

      // 填充表单数据
      Object.keys(meetingForm).forEach(key => {
        meetingForm[key] = meetingData[key] || '';
      });

      isEdit.value = true;
      editDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || '获取会议详情失败');
    }
  } catch (error) {
    console.error('获取会议详情失败:', error);
    ElMessage.error('获取会议详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 删除会议
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除"${row.meetingTheme}"会议吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 执行删除操作
      const response = await deleteMeetingLog(row.id);

      if (response.data.code === 200) {
        ElMessage.success(`删除"${row.meetingTheme}"会议成功`);
        // 刷新列表
        fetchMeetings();
      } else {
        ElMessage.error(response.data.msg || '删除会议失败');
      }
    } catch (error) {
      console.error('删除会议失败:', error);
      ElMessage.error('删除会议失败，请稍后重试');
    }
  }).catch(() => { });
};

// 签到管理
const handleAttendance = (row) => {
  // 加载该会议的签到列表
  attendeesLoading.value = true;
  currentMeeting.value = { ...row };

  // 模拟API请求加载签到数据
  setTimeout(() => {
    attendeeList.value = [
      {
        id: '1',
        name: '张三',
        department: '市场部',
        position: '经理',
        attendance_status: 'present',
        leave_reason: '',
        sign_time: '2023-06-15 14:20'
      },
      {
        id: '2',
        name: '李四',
        department: '技术部',
        position: '工程师',
        attendance_status: 'present',
        leave_reason: '',
        sign_time: '2023-06-15 14:15'
      },
      {
        id: '3',
        name: '王五',
        department: '人事部',
        position: '主管',
        attendance_status: 'leave',
        leave_reason: '出差',
        sign_time: ''
      },
      {
        id: '4',
        name: '赵六',
        department: '财务部',
        position: '会计',
        attendance_status: 'present',
        leave_reason: '',
        sign_time: '2023-06-15 14:25'
      },
      {
        id: '5',
        name: '钱七',
        department: '行政部',
        position: '文员',
        attendance_status: 'absent',
        leave_reason: '',
        sign_time: ''
      }
    ];
    attendeesLoading.value = false;
    attendanceDialogVisible.value = true;
  }, 500);
};

// 搜索党员
const searchAttendees = () => {
  // 根据关键词搜索党员
  // 实际项目中应调用API进行搜索
  console.log('搜索党员:', attendanceSearchKeyword.value);
};

// 添加党员对话框
const handleAddAttendees = () => {
  // 加载可添加的党员列表
  // 模拟API请求
  setTimeout(() => {
    availableAttendees.value = [
      {
        id: '6',
        name: '孙八',
        department: '市场部',
        position: '主管'
      },
      {
        id: '7',
        name: '周九',
        department: '技术部',
        position: '程序员'
      },
      {
        id: '8',
        name: '吴十',
        department: '销售部',
        position: '销售代表'
      },
      {
        id: '9',
        name: '郑十一',
        department: '人事部',
        position: '招聘专员'
      },
      {
        id: '10',
        name: '王十二',
        department: '财务部',
        position: '出纳'
      }
    ];
    addAttendeesDialogVisible.value = true;
  }, 300);
};

// 处理党员选择变化
const handleSelectionChange = (selection) => {
  selectedAttendees.value = selection;
};

// 确认添加党员
const confirmAddAttendees = () => {
  if (selectedAttendees.value.length === 0) {
    ElMessage.warning('请选择要添加的党员');
    return;
  }

  // 获取当前时间
  const now = new Date();
  const signTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

  // 将选中的党员添加到签到列表
  selectedAttendees.value.forEach(attendee => {
    attendeeList.value.push({
      ...attendee,
      attendance_status: 'present',
      leave_reason: '',
      sign_time: signTime
    });
  });

  // 更新参会人数和参会率
  updateAttendanceStats();

  ElMessage.success(`成功添加${selectedAttendees.value.length}名党员`);
  addAttendeesDialogVisible.value = false;
};

// 移除党员
const handleRemoveAttendee = (row) => {
  ElMessageBox.confirm(
    `确定要移除党员"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = attendeeList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      attendeeList.value.splice(index, 1);

      // 更新参会人数和参会率
      updateAttendanceStats();
    }
    ElMessage.success(`成功移除党员"${row.name}"`);
  }).catch(() => { });
};

// 更新参会统计数据
const updateAttendanceStats = () => {
  // 计算实际参会人数（已签到的人数）
  const presentCount = attendeeList.value.filter(item => item.attendance_status === 'present').length;

  // 更新当前会议的参会信息
  currentMeeting.value.attendance_count = presentCount;
  currentMeeting.value.attendance_rate = Math.round((presentCount / currentMeeting.value.expected_count) * 100);

  // 更新会议列表中的数据
  const index = meetingList.value.findIndex(item => item.id === currentMeeting.value.id);
  if (index !== -1) {
    meetingList.value[index].attendance_count = presentCount;
    meetingList.value[index].attendance_rate = currentMeeting.value.attendance_rate;
  }
};

// 处理签到状态变化
const handleAttendanceStatusChange = (row) => {
  // 如果不是请假，清空请假原因
  if (row.attendance_status !== 'leave') {
    row.leave_reason = '';
  }

  // 如果是签到，设置签到时间
  if (row.attendance_status === 'present' && !row.sign_time) {
    const now = new Date();
    row.sign_time = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
  }

  // 更新参会统计
  updateAttendanceStats();
};

// 处理请假原因变化
const handleLeaveReasonChange = (row) => {
  console.log('请假原因变化:', row.name, row.leave_reason);
};

// 保存签到信息
const saveAttendance = () => {
  // 保存签到信息
  // 实际项目中应调用API保存数据
  ElMessage.success('签到信息保存成功');
  attendanceDialogVisible.value = false;

  // 如果会议状态是待召开且已经有人签到，自动将状态修改为已召开
  if (currentMeeting.value.meetingStatus === 1 && currentMeeting.value.attendance_count > 0) {
    currentMeeting.value.meetingStatus = 2;

    // 更新会议列表中的状态
    const index = meetingList.value.findIndex(item => item.id === currentMeeting.value.id);
    if (index !== -1) {
      meetingList.value[index].meetingStatus = 2;
    }
  }
};

// 会议纪要
const handleMinutes = async (row) => {
  try {
    loading.value = true;
    // 获取会议详情
    const response = await getMeetingLogById(row.id);

    if (response.data.code === 200) {
      currentMeeting.value = response.data.data || {};

      // 初始化会议纪要表单
      minutesForm.id = currentMeeting.value.id;
      minutesForm.actual_count = currentMeeting.value.attendance_count || 0;
      minutesForm.topics = currentMeeting.value.topics || '';
      minutesForm.discussion = currentMeeting.value.discussion || '';
      minutesForm.resolution = currentMeeting.value.resolution || '';
      minutesForm.files = currentMeeting.value.files || [];

      minutesDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || '获取会议详情失败');
    }
  } catch (error) {
    console.error('获取会议详情失败:', error);
    ElMessage.error('获取会议详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理文件变化
const handleFileChange = (file, fileList) => {
  minutesForm.files = fileList;
};

// 处理文件移除
const handleFileRemove = (file, fileList) => {
  minutesForm.files = fileList;
};

// 提交会议纪要
const submitMinutes = async () => {
  if (!minutesFormRef.value) return;

  minutesFormRef.value.validate(async (valid) => {
    if (!valid) return;

    submitting.value = true;
    try {
      // 构建提交数据
      const submitData = {
        id: currentMeeting.value.id,
        resolution: minutesForm.resolution,
        topics: minutesForm.topics,
        discussion: minutesForm.discussion,
        attendance_count: minutesForm.actual_count,
        // 其他需要更新的字段
        files: minutesForm.files
      };

      // 调用API更新数据
      const response = await updateMeetingLog(submitData);

      if (response.data.code === 200) {
        ElMessage.success('会议纪要保存成功');
        minutesDialogVisible.value = false;
        // 刷新列表
        fetchMeetings();
      } else {
        ElMessage.error(response.data.msg || '提交会议纪要失败');
      }
    } catch (error) {
      console.error('提交会议纪要失败:', error);
      ElMessage.error('提交会议纪要失败，请稍后重试');
    } finally {
      submitting.value = false;
    }
  });
};

// 提交会议表单
const submitMeeting = async () => {
  if (!meetingFormRef.value) return;

  meetingFormRef.value.validate(async (valid) => {
    if (!valid) return;

    submitting.value = true;
    try {
      // 调用API提交数据
      let response;

      if (isEdit.value) {
        // 更新已有记录
        response = await updateMeetingLog(meetingForm);
      } else {
        // 创建新记录
        response = await addMeetingLog(meetingForm);
      }

      if (response.data.code === 200) {
        ElMessage.success(isEdit.value ? '更新会议成功' : '添加会议成功');
        editDialogVisible.value = false;
        // 刷新列表
        fetchMeetings();
      } else {
        ElMessage.error(response.data.msg || (isEdit.value ? '更新会议失败' : '添加会议失败'));
      }
    } catch (error) {
      console.error('提交会议失败:', error);
      ElMessage.error('提交会议失败，请稍后重试');
    } finally {
      submitting.value = false;
    }
  });
};

// 即时搜索
const debounceSearch = () => {
  fetchMeetings();
};

// 获取文件名
const getFileName = (filePath) => {
  const parts = filePath.split('/');
  return parts[parts.length - 1];
};

// 判断是否为图片文件
const isImageFile = (filePath) => {
  const imageExtensions = ['.jpg', '.png', '.jpeg'];
  const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();
  return imageExtensions.includes(ext);
};

// 下载文件
const downloadFile = (fileUrl) => {
  if (!fileUrl) {
    ElMessage.warning('文件URL不存在');
    return;
  }

  try {
    // 创建一个临时的a标签
    const link = document.createElement('a');
    link.href = fileUrl;
    link.target = '_blank';

    // 从URL中提取文件名
    const fileName = getFileName(fileUrl);
    link.download = fileName;

    // 添加到body
    document.body.appendChild(link);

    // 触发点击
    link.click();

    // 移除元素
    document.body.removeChild(link);

    ElMessage.success('下载请求已发送');
  } catch (error) {
    console.error('下载文件失败:', error);
    ElMessage.error('下载文件失败，请稍后重试');
  }
};

// 格式化日期时间
const formatDateTime = (timestamp) => {
  const date = new Date(timestamp);
  return date.toLocaleString();
};

// 文件上传前检查
const beforeUpload = (file) => {
  const validTypes = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
  const isValidType = validTypes.includes(file.type);
  if (!isValidType) {
    ElMessage.error('只能上传JPG、PNG、PDF、DOC、DOCX格式的文件!');
    return false;
  }

  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }

  return true;
};

// 处理上传成功
const handleUploadSuccess = (response, file, fileList) => {
  console.log(response);
  if (response.code === 200 && response.data) {
    meetingForm.filePath = response.data.imgUrl || response.data;
    meetingForm.filePath = 'http://127.0.0.1:8081/' + meetingForm.filePath;
    ElMessage.success('文件上传成功');
  } else {
    ElMessage.error(response.msg || '文件上传失败');
  }
};

// 处理上传错误
const handleUploadError = (error, file, fileList) => {
  console.error('上传错误:', error);
  ElMessage.error('文件上传失败: ' + (error.message || '未知错误'));
};
</script>

<style scoped>
.branch-meeting-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 30px;
}

.search-card {
  margin-bottom: 30px;
}

.table-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: stretch;
}

.action-buttons .el-button {
  margin-left: 0 !important;
  width: 100%;
  justify-content: center;
  padding-left: 10px;
  padding-right: 10px;
  text-align: center;
}

.file-preview {
  margin-top: 10px;
  text-align: center;
}

.file-info {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-users-info {
  margin-top: 5px;
  font-size: 12px;
  color: #409EFF;
}

.meeting-people {
  max-width: 100%;
  word-break: break-all;
  padding: 5px 0;
}
</style>